//
//  VideoDetailSectionOneCell.m
//  copyrightTrading
//
//  Created by edz on 2020/10/9.
//  Copyright © 2020 郭子一. All rights reserved.
//

#import "VideoDetailSectionOneCell.h"

@interface VideoDetailSectionOneCell ()

@property (nonatomic, strong) UILabel *priceLabel; // 价格
@property (nonatomic, strong) UILabel *titleLab; // 名称
@property (nonatomic, strong) UIButton *buyBtn;     // 购买
@property (nonatomic, strong) UIButton *reportBtn; // 申诉举报
@property (nonatomic, strong) UILabel *contentLabel; // 内容简介
@property (nonatomic, strong) UIButton *downloadBtn;     // 下载
@property (nonatomic, strong) UIButton *addCartBtn;     // 加入购物车
@property (nonatomic, strong) UIButton *buyCopyrightBtn;     // 版权购买
@property (nonatomic, strong) UIButton *shareBtn;     // 分享

@property (strong, nonatomic) NSURLSessionDownloadTask *downloadTask;
@end

@implementation VideoDetailSectionOneCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.contentView.backgroundColor = RGB_VALUE(0xF5F5F5);
        [self setupUI];
    }
    return self;
}

- (void)setupUI
{
    UIView *bgView = [UIView new];
    bgView.backgroundColor = UIColor.whiteColor;
    [self.contentView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.offset(10);
    }];
    
//    NSMutableAttributedString *mutAttribts = [[NSMutableAttributedString alloc]initWithString:@"《泉城夜宴》\n济南新版城市宣传片"];
//    [mutAttribts setAttributes:@{NSFontAttributeName : JSS_MEDIUM_FONT_2}
//                         range:NSMakeRange(0, 6)];
//    self.contentLabel.attributedText = mutAttribts;
    
    self.priceLabel = [UILabel new];
    self.priceLabel.font = JSS_MEDIUM_FONT_7;
    self.priceLabel.textColor = RGB_VALUE(0x969696);
    [bgView addSubview:self.priceLabel];
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-130);
        make.top.offset(16);
        make.height.mas_equalTo(21);
    }];
    
    self.titleLab = [UILabel new];
    self.titleLab.font = JSS_MEDIUM_FONT_7;
    self.titleLab.text = @"一叶小舟";
    [bgView addSubview:self.titleLab];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.priceLabel.mas_left);
        make.top.equalTo(self.priceLabel.mas_bottom);
        make.right.offset(-130);
        make.height.mas_equalTo(24);
    }];
    
    self.buyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.buyBtn setTitle:@"立即购买" forState:UIControlStateNormal];
    [self.buyBtn setImage:[UIImage imageNamed:@"dollars"] forState:UIControlStateNormal];
    [self.buyBtn setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    self.buyBtn.backgroundColor = RGB_VALUE(0xFFC183);
    self.buyBtn.titleLabel.font = JSS_MEDIUM_FONT_5;
    self.buyBtn.layer.masksToBounds = YES;
    self.buyBtn.layer.cornerRadius = 5;
    [self.buyBtn layoutButtonWithEdgeInsetsStyle:DVButtonEdgeInsetsStyleLeft imageTitleSpace:3];
    [bgView addSubview:self.buyBtn];
    [self.buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(20);
        make.right.offset(-22);
        make.width.mas_equalTo(99);
        make.height.mas_equalTo(36);
    }];
    
    // 110
    self.contentLabel = [UILabel new];
    self.contentLabel.font = JSS_MEDIUM_FONT_3;
    self.contentLabel.textColor = RGB_VALUE(0x969696);
    self.contentLabel.numberOfLines = 0;
    self.contentLabel.text = @"编号：2237562174\n版权：JVNMedia\n文件格式：JPEG\n所属类别：文化\n文件大小：2.36M\n上传时间：2020-09-22\n素材简介：素材简介素材简介素材简介素材简介素材简介素材 简介素材简介素材简介素材简介素材简介素材简介 素材简介素材简介素材简介素材简介素材简介素材 简介素材简素材简介素材简介。";
    [bgView addSubview:self.contentLabel];
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(11);
        make.right.offset(-21);
        make.top.equalTo(self.titleLab.mas_bottom).offset(7);
        make.height.mas_equalTo(141);
    }];

    self.reportBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.reportBtn layoutButtonWithEdgeInsetsStyle:DVButtonEdgeInsetsStyleLeft imageTitleSpace:3];
//    [self.reportBtn setTitle:@"立即购买" forState:UIControlStateNormal];
    [self.reportBtn setImage:[UIImage imageNamed:@"report"] forState:UIControlStateNormal];
//    [self.reportBtn setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    self.reportBtn.titleLabel.font = JSS_MEDIUM_FONT_5;
    [bgView addSubview:self.reportBtn];
    [self.reportBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.buyBtn.mas_bottom).offset(10);
        make.right.offset(-22);
        make.width.mas_equalTo(21);
        make.height.mas_equalTo(21);
    }];

    self.downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.downloadBtn setTitle:@"立即下载" forState:UIControlStateNormal];
    [self.downloadBtn setImage:[UIImage imageNamed:@"downLoad"] forState:UIControlStateNormal];
    [self.downloadBtn setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    self.downloadBtn.titleLabel.font = JSS_MEDIUM_FONT_3;
    self.downloadBtn.backgroundColor = RGB_VALUE(0xFF6667);
    self.downloadBtn.layer.masksToBounds = YES;
    self.downloadBtn.layer.cornerRadius = 5;
    [self.downloadBtn layoutButtonWithEdgeInsetsStyle:DVButtonEdgeInsetsStyleTop imageTitleSpace:1];
    [bgView addSubview:self.downloadBtn];
    [self.downloadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentLabel.mas_bottom).offset(10);
        make.left.offset(18);
        make.height.mas_equalTo(54);
    }];
    
    self.addCartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.addCartBtn setTitle:@"加入购物车" forState:UIControlStateNormal];
    [self.addCartBtn setImage:[UIImage imageNamed:@"MineCart"] forState:UIControlStateNormal];
    [self.addCartBtn setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    self.addCartBtn.titleLabel.font = JSS_MEDIUM_FONT_3;
    self.addCartBtn.backgroundColor = RGB_VALUE(0xFF9000);
    self.addCartBtn.layer.masksToBounds = YES;
    self.addCartBtn.layer.cornerRadius = 5;
    [self.addCartBtn layoutButtonWithEdgeInsetsStyle:DVButtonEdgeInsetsStyleTop imageTitleSpace:1];
    [bgView addSubview:self.addCartBtn];
    [self.addCartBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentLabel.mas_bottom).offset(10);
        make.left.equalTo(self.downloadBtn.mas_right).offset(5);
        make.height.mas_equalTo(54);
        make.width.equalTo(self.downloadBtn);
    }];
    
    self.buyCopyrightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.buyCopyrightBtn setTitle:@"版权购买" forState:UIControlStateNormal];
    [self.buyCopyrightBtn setImage:[UIImage imageNamed:@"copyRight"] forState:UIControlStateNormal];
    [self.buyCopyrightBtn setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    self.buyCopyrightBtn.titleLabel.font = JSS_MEDIUM_FONT_3;
    self.buyCopyrightBtn.backgroundColor = RGB_VALUE(0xD3BB8C);
    self.buyCopyrightBtn.layer.masksToBounds = YES;
    self.buyCopyrightBtn.layer.cornerRadius = 5;
    [self.buyCopyrightBtn layoutButtonWithEdgeInsetsStyle:DVButtonEdgeInsetsStyleTop imageTitleSpace:1];
    [bgView addSubview:self.buyCopyrightBtn];
    [self.buyCopyrightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentLabel.mas_bottom).offset(10);
        make.left.equalTo(self.addCartBtn.mas_right).offset(5);
        make.height.mas_equalTo(54);
        make.width.equalTo(self.addCartBtn);
    }];
    
    self.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shareBtn setTitle:@"分享" forState:UIControlStateNormal];
    [self.shareBtn setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [self.shareBtn setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    self.shareBtn.titleLabel.font = JSS_MEDIUM_FONT_3;
    self.shareBtn.backgroundColor = RGB_VALUE(0x55A526);
    self.shareBtn.layer.masksToBounds = YES;
    self.shareBtn.layer.cornerRadius = 5;
    [self.shareBtn layoutButtonWithEdgeInsetsStyle:DVButtonEdgeInsetsStyleTop imageTitleSpace:1];
    [bgView addSubview:self.shareBtn];
    [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentLabel.mas_bottom).offset(10);
        make.left.equalTo(self.buyCopyrightBtn.mas_right).offset(5);
        make.height.mas_equalTo(54);
        make.width.equalTo(self.buyCopyrightBtn);
        make.right.offset(-18);
    }];
    
    self.buyBtn.tag = 666;
    self.reportBtn.tag = 667;
    self.downloadBtn.tag = 668;
    self.addCartBtn.tag = 669;
    self.buyCopyrightBtn.tag = 670;
    self.shareBtn.tag = 671;
    
    [self.buyBtn addTarget:self action:@selector(buyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.reportBtn addTarget:self action:@selector(buyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.downloadBtn addTarget:self action:@selector(buyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.addCartBtn addTarget:self action:@selector(buyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.buyCopyrightBtn addTarget:self action:@selector(buyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.shareBtn addTarget:self action:@selector(buyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setDataDic:(NSDictionary *)dataDic
{
    _dataDic = dataDic;
    if ([dataDic[@"price"] isEqual:@"免费"]) {
        self.priceLabel.text = @"免费";
    } else if(!NULLString(dataDic[@"price"])) {
        NSMutableAttributedString *mutAttribts = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@元",dataDic[@"price"]]];
        [mutAttribts setAttributes:@{NSForegroundColorAttributeName:RGB_VALUE(0xFF9D00),NSFontAttributeName : JSS_MEDIUM_FONT_4}
                             range:NSMakeRange([dataDic[@"price"] length], 1)];
        self.priceLabel.attributedText = mutAttribts;
    }
    
    self.titleLab.text = dataDic[@"title"];
    
    CGSize sizes = [dataDic[@"intro"] boundingRectWithSize:CGSizeMake(kDeviceWidth - 50, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:JSS_MEDIUM_FONT_3} context:nil].size;
    self.contentLabel.text = [NSString stringWithFormat:@"编号：%@\n版权：%@\n文件格式：%@\n所属类别：%@\n文件大小：%@\n上传时间：%@\n素材简介：%@",dataDic[@"uuid"],dataDic[@"copyright"],dataDic[@"suffix"],dataDic[@"sort_name"],dataDic[@"size"],dataDic[@"create_day"],dataDic[@"intro"]];
    [self.contentLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(sizes.height + 140);
    }];
}

//https://www.apple.com/105/media/cn/mac/family/2018/46c4b917_abfd_45a3_9b51_4e3054191797/films/bruce/mac-bruce-tpl-cn-2018_1280x720h.mp4

- (void)buyBtnClick:(UIButton *)sender
{
//    if (sender.tag == 668) {
//        [self downLoadData];
//    } else {
//        [self downLoadData1];
//    }
    
    if ([self.delegate respondsToSelector:@selector(VideoDetailSectionOneCellClickBtn:)]) {
        [self.delegate VideoDetailSectionOneCellClickBtn:sender.tag];
    }
}

- (void)downLoadData
{
    [TipView showMessage:@"下载中,请稍等"];
    NSString *movieUrl = @"https://www.apple.com/105/media/cn/mac/family/2018/46c4b917_abfd_45a3_9b51_4e3054191797/films/bruce/mac-bruce-tpl-cn-2018_1280x720h.mp4";
//    NSString *movieUrl = @"http://39.105.153.211/uploads/file_material/20200807/159680640205a72a8f074c2907.mp3";
    
//    NSString *movieUrl = self.dataDic[@"compress_url"];
    NSString *name = [[NSFileManager defaultManager] displayNameAtPath:movieUrl];
    NSString *filePath = [[self videoFilePath] stringByAppendingPathComponent:name];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (fileExists) {
        NSLog(@"视频==已经缓存过了！");
        return;
    }
    NSString *documentsDirecroty = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *fullPath = [NSString stringWithFormat:@"%@%@",documentsDirecroty,@"50a93e8ec43ba98091d7fa5bf5f71769_compress.mp4"];
//    NSString *fullPath = [NSString stringWithFormat:@"%@%@",documentsDirecroty,@"159680640205a72a8f074c2907.mp3"];
    NSURL *url = [NSURL URLWithString:movieUrl];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    if (!self.downloadTask) {
        self.downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
            dispatch_async(dispatch_get_main_queue(), ^{
    //            NSLog(@"视频==下载进度%.2f",1.0/downloadProgress.totalUnitCount);
                // @property int64_t totalUnitCount;     需要下载文件的总大小

                // @property int64_t completedUnitCount; 当前已经下载的大小

                // 给Progress添加监听 KVO

                NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);

            });
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            return [NSURL fileURLWithPath:fullPath];
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            NSString *name = [[NSFileManager defaultManager] displayNameAtPath:url.path];
            NSString *savefilePath = [[self videoFilePath] stringByAppendingPathComponent:name];
            [[NSFileManager defaultManager] moveItemAtPath:filePath.path toPath:savefilePath error:nil];
            BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:savefilePath];
            
            if (isExists)
            {
                NSURL *videoUrl = [NSURL fileURLWithPath:savefilePath];
                NSLog(@"视频==已经缓存过了！！！！%@",videoUrl);
            } else {
                NSLog(@"视频==缓存好了！！！！");
            }
        }];
        [self.downloadTask resume];
    }
}

- (NSString *)videoFilePath {
    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [path stringByAppendingPathComponent:kDVDownLoadFileName];
    BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (!isExists)
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return filePath;
}

- (void)downLoadData1
{
    NSString *movieUrl = @"https://www.apple.com/105/media/cn/mac/family/2018/46c4b917_abfd_45a3_9b51_4e3054191797/films/bruce/mac-bruce-tpl-cn-2018_1280x720h.mp4";
//    NSString *movieUrl = @"http://39.105.153.211/uploads/file_material/20200807/159680640205a72a8f074c2907.mp3";
    
//    NSString *movieUrl = self.dataDic[@"compress_url"];
    NSString *name = [[NSFileManager defaultManager] displayNameAtPath:movieUrl];
    NSString *filePath = [[self videoFilePath] stringByAppendingPathComponent:name];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (fileExists) {
        NSLog(@"视频==已经缓存过了！");
        return;
    }
    NSString *documentsDirecroty = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *fullPath = [NSString stringWithFormat:@"%@%@",documentsDirecroty,movieUrl];
//    NSString *fullPath = [NSString stringWithFormat:@"%@%@",documentsDirecroty,@"159680640205a72a8f074c2907.mp3"];
    NSURL *url = [NSURL URLWithString:movieUrl];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    self.downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
//            NSLog(@"视频==下载进度%.2f",1.0/downloadProgress.totalUnitCount);
            // @property int64_t totalUnitCount;     需要下载文件的总大小

            // @property int64_t completedUnitCount; 当前已经下载的大小

            // 给Progress添加监听 KVO

            NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);

        });
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSString *name = [[NSFileManager defaultManager] displayNameAtPath:url.path];
        NSString *savefilePath = [[self videoFilePath] stringByAppendingPathComponent:name];
        [[NSFileManager defaultManager] moveItemAtPath:filePath.path toPath:savefilePath error:nil];
        BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:savefilePath];
        
        if (isExists)
        {
            NSURL *videoUrl = [NSURL fileURLWithPath:savefilePath];
            NSLog(@"视频==已经缓存过了！！！！%@",videoUrl);
        } else {
            NSLog(@"视频==缓存好了！！！！");
        }
    }];
    [self.downloadTask resume];
    
}
@end
